package com.dd.dus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dc.base.domain.DBaseEntity;
import com.dd.dc.entity.users.DPermission;
import com.dd.dc.entity.users.DRolePermissionRelation;
import com.dd.dc.entity.users.DUserRoleRelation;
import com.dd.dus.mapper.DPermissionMapper;
import com.dd.dus.mapper.DRoleMapper;
import com.dd.dus.mapper.DRolePermissionRelationMapper;
import com.dd.dus.mapper.DUserRoleRelationMapper;
import com.dd.dus.service.IDPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限/菜单信息表 服务实现类
 * </p>
 *
 * @author JueDream
 * @since 2021-03-12
 */
@Service
public class DPermissionServiceImpl extends ServiceImpl<DPermissionMapper, DPermission> implements IDPermissionService {

    @Autowired
    DPermissionMapper permissionMapper;

    @Autowired
    DRoleMapper roleMapper;

    @Autowired
    DUserRoleRelationMapper userRoleRelationMapper;

    @Autowired
    DRolePermissionRelationMapper rolePermissionRelationMapper;

    @Override
    public List<DPermission> findPermissionByUserId(Integer userId) {
        // 根据用户编号查询角色信息
        // 菜单
        List<DPermission> permissionList = new ArrayList<>();
        QueryWrapper queryWrapper = null;
        if (userId > 0) {
            // 根据用户编号查询角色编号
            DUserRoleRelation userRoleRelation = new DUserRoleRelation().setUserId(userId);
            queryWrapper = new QueryWrapper(userRoleRelation);
            userRoleRelation = userRoleRelationMapper.selectOne(queryWrapper);
            // 根据角色查询权限菜单信息,遍历父子关系
            DRolePermissionRelation rolePermissionRelation = new DRolePermissionRelation().setRoleId(userRoleRelation.getRoleId());
            queryWrapper = new QueryWrapper(rolePermissionRelation);
            List<DRolePermissionRelation> rolePermissionRelations = rolePermissionRelationMapper.selectList(queryWrapper);
            List<Integer> perIds = rolePermissionRelations.stream().map(rp -> rp.getPId()).collect(Collectors.toList());
            permissionList = permissionMapper.selectBatchIds(perIds);
        }else{
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("DEL_FLG", 0);
            permissionList = permissionMapper.selectList(queryWrapper);
        }
        return this.queryMenuList(permissionList);
    }

    @Override
    public List<DPermission> findPermissionByRoleId(List<Integer> roleIds) {
        List<DPermission> permissionList = new ArrayList<>();
        roleIds = Optional.ofNullable(roleIds).orElse(new ArrayList<>());
        // 菜单
        LambdaQueryWrapper<DRolePermissionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DRolePermissionRelation::getRoleId, roleIds);
        List<DRolePermissionRelation> relations = rolePermissionRelationMapper.selectList(queryWrapper);
        List<Integer> pIds = Optional.ofNullable(relations).orElse(new ArrayList<>())
                .stream().map(rp -> rp.getPId()).collect(Collectors.toList());
        if (pIds.size() > 0){
            permissionList = permissionMapper.selectBatchIds(pIds);
        }else{
            LambdaQueryWrapper<DPermission> queryWrapper1 = new LambdaQueryWrapper();
            queryWrapper1.eq(DPermission::getDelFlg, 0);
            permissionList = permissionMapper.selectList(queryWrapper1);
        }
        return this.queryMenuList(permissionList);
    }

    @Override
    public Page<DPermission> queryRoleList(int page, int limit, String permissionName) {
        Page<DPermission> permissionIPage = new Page<>(page, limit);
        LambdaQueryWrapper<DPermission> queryWrapper = new LambdaQueryWrapper<DPermission>();
        queryWrapper.like(DPermission::getPName, permissionName);
        permissionIPage = permissionMapper.selectPage(permissionIPage, queryWrapper);
        permissionIPage.setTotal(permissionIPage.getRecords().size());
        return permissionIPage;
    }

    @Override
    public Integer insert(DPermission permission) {
        permissionMapper.insert(permission);
        return permission.getPId();
    }

    /**
     * 组合菜单权限树形结构
     * @param permissionList
     * @return
     */
    private List<DPermission> queryMenuList(List<DPermission> permissionList){
        List<DPermission> menuVoList = new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream().forEach(permission -> {
            if(0 == permission.getPParentId()){
                //上级节点
                menuVoList.add(permission);
            }
        });
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream().forEach((permission) -> {
            if(permission.getPParentId() > 0){
                //子节点
                menuVoList.forEach((permissionP) -> {
                    if(permissionP.getPId().equals(permission.getPParentId())){
                        permissionP.getChildren().add(permission);
                    }
                });
            }
        });
        return menuVoList;
    }
}
